package com.yoyo.schedule.task_manager;

import com.yoyo.schedule.DateFormats;
import com.yoyo.schedule.expression.CronExpression;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Timer;

@Slf4j
class PauseOrResumeTimerTask extends java.util.TimerTask {
    public static int type_pause = 1;
    public static int type_resume = 2;

    AbstractScheduleManager abstractScheduleManager;
    Timer timer;
    int type;
    String cronExpression;

    public PauseOrResumeTimerTask(AbstractScheduleManager abstractScheduleManager, Timer timer, int type, String cronExpression) {
        this.abstractScheduleManager = abstractScheduleManager;
        this.timer = timer;
        this.type = type;
        this.cronExpression = cronExpression;
    }

    public void run() {
        try {
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
            this.cancel();
            Date nowDate = new Date(System.currentTimeMillis());
            CronExpression cronExpression = new CronExpression(this.cronExpression);
            Date nextDateTime = cronExpression.getNextTimeAfter(nowDate);
            if (this.type == type_pause) {
                abstractScheduleManager.pause("pause");
                this.abstractScheduleManager.getTaskHandler().setNextRunEndTime(DateFormats.transferDataToString(nextDateTime));
            } else {
                abstractScheduleManager.resume("resume");
                this.abstractScheduleManager.getTaskHandler().setNextRunStartTime(DateFormats.transferDataToString(nextDateTime));
            }
            this.timer.schedule(new PauseOrResumeTimerTask(this.abstractScheduleManager, this.timer, this.type, this.cronExpression), nextDateTime);
        } catch (Throwable ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}
